<?php
 class Products extends CI_Model{
    function __construct(){
        parent::__construct();
    }
    
     /** 
     * Insert data for config
     * @author tien.nguyen
     */
    public function getList($cateId = null){
        $this->db->order_by('products.Ordering ASC');
        $this->db->join('product_categories', 'product_categories.ProductCategoryId =
            products.ProductCategoryId', 'left');
        
        if(!empty($cateId)){
            $this->db->where('product_categories.ProductCategoryId = '.$cateId);
        }
        
        $query = $this->db->get('products');
        $res = $query->result_array();
        return $res;
    }
    
        
    /**
     * Get product by product id
     * @author tien.nguyen
     */
    public function getProduct($productId){
        $query = $this->db->get_where('products', array('ProductId' => $productId));
        return $query->row_array();
    }
    
    /**
     * edit function in config
     * @author tien.nguyen
     */
    public function edit($data, $productId){
        $data = $this->_convertData($data);
        return $this->db->update('products', $data, array('ProductId' => $productId));
    }
    
    /**
     * Delete product id
     * @author tien.nguyen
     */
    public function delete($productId){
       return $this->db->delete('products', array('ProductId' => $productId)); 
    }
    
    /**
     * add product
     * @author tien.nguyen
     */
    public function add($data){
        $data = $this->_convertData($data);
        $data['CreatedDate'] = date('Y-m-d H:m:s');
        return $this->db->insert('products', $data);
    }
    
    /**
     * Get options
     * @author tien.nguyen
     */
    public function getOptions(){
        $this->db->select('products.ProductId, products.ProductName');
        $this->db->from('products');
        $query = $this->db->get();
        $list = $query->result();
        $res = array();
        foreach($list as $item){
            $res[$item->ProductId] = $item->ProductName;
        }
        return $res;
    }
    
    /**
     * Convert data array to array of product
     * @author tien.nguyen
     */
    private function _convertData($data){
        $res = array();
        $arr = array('ProductId', 'ProductName', 'ProductShortDescription', 'ProductDescription', 
            'ProductDetail', 'Visible', 'CreatedDate', 'Image', 'Icon', 'Ordering',
            'Price', 'ProductCategoryId', 'ProductCompare', 'ProductGeneral', 'ProductFuture',
            'ProductPicture', 'DownloadTrial', 'Enviroment');
        foreach($arr as $item){
            if(isset($data[$item])){
                $res[$item] = $data[$item];
            }
        }
        
        //set default value
        $res['Visible'] = isset($res['Visible']) ? $res['Visible'] : 0;
        return $res;
    }
 }
?>